import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import {message} from 'antd'

import { getToken } from './auth'
import { API_PREFIX } from '../config'

export interface HttpResponse<T = unknown> {
  code: number;
	message: string;
  data: T;
}

const Service = axios.create({
  timeout: 7000, // 请求超时时间
  baseURL: API_PREFIX,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

Service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // let each request carry token
    // this example using the JWT token
    // Authorization is a custom headers key
    // please modify it according to the actual situation
    const token = getToken();
    if (token) {
      if (!!!(config.headers)) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    // do something
    return Promise.reject(error);
  }
);
// add response interceptors
Service.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
			message.error(res.message || 'Error', 5);
    
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [50008, 50012, 50014].includes(res.code) &&
        response.config.url !== '/api/user/info'
      ) {
        // TODO token过期清除token
      }
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return res;
  },
  (error) => {
    message.error(error || 'Error', 5);
    return Promise.reject(error);
  }
);


export default Service